//
//  WPSSettingsVC.swift
//  MIFI
//
//  Created by 金嗓子卡卡 on 2019/5/4.
//  Copyright © 2019 NJMifi. All rights reserved.
//

import UIKit
import SVProgressHUD
class WPSSettingsVC: RootVC {

    private let datas : [String] = ["PIN","PBC","Enter PIN"]
    
    private var currentIndex = 0
    
    private var pinString : String?
    
    private var btns : [UIButton] = []
    
    private var ssid = ""
    
    private lazy var tableView: UITableView = {
        let tab = UITableView(frame: CGRect(x: 0, y: naviView!.bottom, width: screenWidth, height: screenHeight - naviView!.bottom), style: .grouped)
        tab.backgroundColor = whiteColor
        tab.rowHeight = 50
        tab.delegate = self
        tab.dataSource = self
        tab.separatorStyle = .none
        tab.isScrollEnabled = false
        return tab
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(tableView)
        getData()
    }
    
    override func configView() {
        configNaviView(title: "WPS")
        rightBtn?.backgroundColor = clearColor
        rightBtn?.setTitle("OK", for: .normal)
        rightBtn?.setTitleColor(whiteColor, for: .normal)
        rightBtn?.titleLabel?.font = UIFont.systemFont(ofSize: 18)
    }
    
    override func rightBtnClicked(sender: UIButton) {
        let mode = datas[currentIndex]
        let pin = currentIndex == 0 ? pinString : nil
        if currentIndex == 0 && pin == nil {
            SVProgressHUD.showError(withStatus: "Please enter your PIN.")
            return
        }
        net_setWPS(mode: mode, pin: pin, ssid: ssid) {[weak self] (success) in
            if success {
                self?.navigationController?.popViewController(animated: true)
            }
        }
    }
    
    private func getData() {
        net_getDeviceInfoList {[weak self] (model) in
            if model != nil {
                self?.ssid = model!.sSID1!
                if model?.wpsMode?.caseInsensitiveCompare("PIN") == .orderedSame {
                    self?.currentIndex = 0
                }else {
                    self?.currentIndex = 1
                }
            }
            self?.tableView.reloadData()
        }
    }
    
    @objc private func changeWps(sender:UIButton) {
        guard currentIndex != sender.tag else {
            return
        }
        _ = btns.map{
            $0.isSelected = false
        }
        sender.isSelected = true
        currentIndex = sender.tag
        tableView.reloadData()
    }

}

extension WPSSettingsVC : UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return currentIndex == 0 ? 3 : 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        cell.textLabel?.text = datas[indexPath.row]
        cell.textLabel?.font = UIFont.systemFont(ofSize: 18)
        cell.textLabel?.textColor = textGray
        cell.selectionStyle = .none
        if indexPath.row == 2 {
            cell.accessoryType = .disclosureIndicator
        }else {
            let btn = UIButton(frame: CGRect(x: 0, y: 10, width: 30, height: 30))
            btn.right = screenWidth - 16
            btn.setImage(UIImage(named: "icon_round_normal"), for: .normal)
            btn.setImage(UIImage(named: "icon_round_selected"), for: .selected)
            btn.isSelected = currentIndex == indexPath.row
            btn.addTarget(self, action: #selector(changeWps(sender:)), for: .touchUpInside)
            btn.tag = indexPath.row
            cell.contentView.addSubview(btn)
            if btns.count < 2 {
                btns.append(btn)
            }
        }

        let line = UIView(frame: CGRect(x: 8, y: 50 - 0.5, width: screenWidth - 16, height: 0.5))
        line.backgroundColor = textGray
        cell.contentView.addSubview(line)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard indexPath.row == 2 else {
            return
        }
        let pin = pinString == nil ? "" : pinString!
        let alertView = InputAlertView(input: pin, title: "Enter PIN")
        alertView.handle = ({[weak self] content in
            self?.pinString = content
        })
        let alertVC = CustomAlertVC(contentType: .animation(alertView))
        alertVC.show()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}
